package com.woniu.airent.controller;

import com.github.pagehelper.PageInfo;
import com.woniu.airent.dto.UserDto;
import com.woniu.airent.service.UserDtoService;
import com.woniu.airent.utils.MD5Util;
import com.woniu.airent.utils.SmsUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Controller
@RequestMapping("userDto")
public class UserDtoController {

    @Autowired
    UserDtoService userDtoService;

    /**
     * 用户注册
     * MD5盐值加密用户密码
     * @param userDto   获取用户注册的信息
     * @return 1：产生了bug
     * @return 2:注册成功
     * @return 3:用户名已存在
     */
    @RequestMapping("/register")
    @ResponseBody
    public String register(UserDto userDto){
        UserDto u = userDtoService.findUserByUserName(userDto.getUserName());
        if (u==null){
            userDto.setUserPwd(MD5Util.md5("MD5",userDto.getUserPwd(),userDto.getUserName(),1024));
            Integer i = userDtoService.addUser(userDto);
            if (i == null){
                //发生未知错误
                return "1";
            }else {
                //用户添加成功
                return "2";
            }
        }else {
            //用户名已存在
            return "3";
        }
    }


    /**
     * 用户名密码登录，通过shiro来实现，登录成功就进入主页面，否则返回登录页面
     * @param userDto   接收到的用户信息
     * @param model     将错误信息放到作用域里去
     * @return  页面跳转
     */
    @RequestMapping("/login")
    public String login(UserDto userDto, Model model,HttpServletRequest request){
        String code = (String) request.getSession().getAttribute("code");
        if (code != null){
            request.getSession().removeAttribute("code");
        }
        Subject currentUser = SecurityUtils.getSubject();
        if(!currentUser.isAuthenticated()){
            UsernamePasswordToken token = new UsernamePasswordToken(userDto.getUserName(),userDto.getUserPwd());
            //      token.setRememberMe(true);
            try {
                currentUser.login(token);
                return "redirect:/index.html";
            }catch (UnknownAccountException uae) {
                model.addAttribute("msg","用户名不存在");
                return "view/login_register";
            }catch (IncorrectCredentialsException ice){
                model.addAttribute("msg","密码错误");
                return "view/login_register";
            }catch (AuthenticationException a) {
                model.addAttribute("msg","系统繁忙");
                return "view/login_register";
            }
        }
        return "view/login_register";
    }

    /**
     * 接收用户手机号，通过手机来获取验证码
     * @param userTel   接收用户手机号
     * @param request   将服务器发送的验证码放到session作用域里去，用户在shiro验证时判断验证码是否正确
     * @return 1：验证码获取成功
     * @return 2：验证码获取失败
     */
    @RequestMapping("/getCode")
    @ResponseBody
    public String getCode(String userTel, HttpServletRequest request){
      String code = SmsUtil.vcode();
      String SmsType =  SmsUtil.getPhonemsg(userTel,code);
      if("true".equals(SmsType)){
          request.getSession().setAttribute("tel",userTel);
          request.getSession().setAttribute("code",code);
          System.out.println(userTel);
          return "1";
      }else {
          return "2";
      }
    }

    /**
     * 通过手机号登录
     * @param userTel   用户手机号
     * @param newCode   用户输入的验证码
     * @param request   将错误信息放到session作用域中，用于在浏览器页面显示
     * @return  1 两次手机号不一致
     * @return  2 验证码错误
     * @return  3 系统繁忙
     * @return  4 成功
     */
    @RequestMapping("/telLogin")
    @ResponseBody
    public String telLogin(String userTel,String newCode,HttpServletRequest request){
        UserDto userDto = null;
        String code = (String) request.getSession().getAttribute("code");
        String tel = (String) request.getSession().getAttribute("tel");
        if (!userTel.equals(tel)){
            return "1";
        }else if (!newCode.equals(code)){
            return "2";
        }else {
            userDto = userDtoService.findUserByTel(userTel);
            if (userDto == null){
                //插入数据库
                String suffix = UUID.randomUUID().toString().substring(0,6);
                String userName = "AR_"+ suffix;
                String userPwd = MD5Util.md5("MD5","",userName,1024);
                Integer i = userDtoService.addUserDto(userName,userPwd,userTel);
                if (i == null){
                    return "3";
                }
            }
            userDto = userDtoService.findUserByTel(userTel);
            String username = userDto.getUserName();
            String password = "";

            Subject subject = SecurityUtils.getSubject();
            if (!subject.isAuthenticated()){
                UsernamePasswordToken token = new UsernamePasswordToken(username,password);
                try {
                    subject.login(token);
                    return "4";
                }catch (AuthenticationException a) {
                    return "3";
                }
            }
            return "3";
        }
    }



    /**
     * 用户退出登录，同时将用户信息从session作用域中抹去
     * @return  页面跳转
     */
    @RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "view/login_register";
    }

    @RequestMapping("/list")
    @ResponseBody
    public PageInfo showAllUser(String userName,
                                @RequestParam(defaultValue = "1") Integer now,
                                @RequestParam(defaultValue = "4") Integer pageSize){
        PageInfo pageInfo = userDtoService.findAllUser(userName,now,pageSize);
        return pageInfo;
    }

    @ResponseBody
    @RequestMapping("/ban")
    public String ban(Integer userId){
        Integer myType = userDtoService.showMyType(userId);
        if (myType == 0){
            return "0";
        }else {
            Integer i = userDtoService.banUser(userId);
            return "1";
        }
    }

    @ResponseBody
    @RequestMapping("/unseal")
    public String unseal(Integer userId){
        Integer myType = userDtoService.showMyType(userId);
        if (myType == 1){
            return "1";
        }else {
            Integer i = userDtoService.unsealUser(userId);
            return "0";
        }
    }
}
